package fantasy;

import java.io.IOException;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.GoogleOAuthHelper;
import com.google.gdata.client.authn.oauth.GoogleOAuthParameters;
import com.google.gdata.client.authn.oauth.OAuthException;
import com.google.gdata.client.authn.oauth.OAuthHmacSha1Signer;

public class GOAuthUpdateTokenServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {

		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
		
		PersistenceManager pm = PMF.get().getPersistenceManager();

		String baseurl = "http://dhpollack944.appspot.com";
		String GOOGLE_CONSUMER_KEY = "dhpollack944.appspot.com";
		String GOOGLE_CONSUMER_SECRET = "5sLdLvnBuYa+fpcWdzie9ndr";
		
		GoogleOAuthParameters oauthParameters = new GoogleOAuthParameters();
		oauthParameters.setOAuthConsumerKey(GOOGLE_CONSUMER_KEY);
		oauthParameters.setOAuthConsumerSecret(GOOGLE_CONSUMER_SECRET);

		GoogleOAuthHelper oauthHelper = new GoogleOAuthHelper(new OAuthHmacSha1Signer());
		oauthHelper.getOAuthParametersFromCallback(req.getQueryString(), oauthParameters);
				
		try {
			String accessToken = oauthHelper.getAccessToken(oauthParameters);
			String accessTokenSecret = oauthParameters.getOAuthTokenSecret();

	    	GOAuth g = new GOAuth();
	    	g.setUserNickname(user.getNickname());
	    	g.setAccessToken(accessToken);
	    	g.setAccessTokenSecret(accessTokenSecret);

	    	try {
	    		pm.makePersistent(g);
	    	} finally {
	    		pm.close();
	    	}
	    	
	    	resp.getWriter().println("Access Token: " + accessToken);
			resp.getWriter().println("Access Token Secret: " + accessTokenSecret);
			
		} catch (OAuthException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		
		resp.getWriter().println("GOAuthUpdateToken");
	}


}
